from django.http import *
from google.appengine.api import users
from db import *
from ytbase.model.auth import *

#authorization decorator
def authorize(cls, operation):
    def decorator(method):
        def new_method(*args, **kwds):
            obj = None
            if kwds.has_key('id') and operation != OPERATION_ADD:
                obj = get_by_str_id(cls, kwds['id'])
                    
            if kwds.has_key('helpers') and kwds['helpers'].has_key('get_auth'): 
                auth = kwds['helpers']['get_auth']((cls, obj))
            else:
                auth = get_auth((cls, obj))

            if auth.has_key(operation):
                auth_result = auth[operation]
            else:
                auth_result = False
                
            if auth_result == False:
                return HttpResponseNotFound()
            
            return method(*args, **kwds)            
        return new_method
    return decorator

#admin authorization decorator
def authorize_admin(method):
    def new_method(*args, **kwds):
        if not users.is_current_user_admin():
            return HttpResponseNotFound()
        return method(*args, **kwds)            
    return new_method
